<template name="location-map-chooser">
	<view>
		<iframe style="position:fixed; top: 44px; width: 100%; height: 100%; border: none; z-index: 3;" :src="url"></iframe>
		<view class="confirm-area">
			<button class="confirm-btn" type="default" @click="onCancel">取消</button>
			<button class="confirm-btn" :type="btnType" @click="onConfirm">确定</button>
		</view>
	</view>
</template>

<script>
	import sys from '../common/sys.js'
	let userLocation;
	window.addEventListener('message', function(event) {
		// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
		var loc = event.data;
		if (loc && loc.module == 'locationPicker') { //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
			userLocation = loc
		}
	}, false);
	export default {
		name: 'location-map-chooser',
		props:{
			gps:{
				type: String,
				default: '',
			},
			type:{
				type: Number,
				default: 5,
			},
			zoom:{
				type: Number,
				default: 15,
			}
		},
		computed:{
			url(){
				// console.log(this.gps, this.type, this.zoom)
				let p = 'https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=BTIBZ-UHNL2-DJCUW-C2UCH-CDQCS-4IBMW&referer=Pray-H5&coordtype='+this.type+'&zoom='+this.zoom
				if(this.gps) p += '&coord='+this.gps
				return p
			}
		},
		data() {
			return {
				run: true,
				selected: false,
				btnType: 'default',
			};
		},
		created() {
			userLocation = null;
			const self = this
			function runRepeat() {
				if (userLocation) {
					self.selected = true
					self.btnType = 'primary'
				}
				if(self.run) setTimeout(runRepeat, 200)
			}
			runRepeat()
		},
		beforeDestroy() {
			this.run = false
		},
		methods: {
			onConfirm() {
				if(userLocation){
					this.$emit('chooselocation', userLocation)
				}else{
					sys.toast('请点击列表项')
				}
				
			},
			onCancel(){
				this.$emit('cancelchoose', userLocation)
			}
		}
	}
</script>

<style>
	.confirm-area {
		position: fixed;
		bottom: 30px;
		left: 0;
		right: 0;
		z-index: 5;
		display: flex;
		justify-content: space-around;
	}

	.confirm-btn {
		width: fit-content;
		box-shadow: 0px 0px 16px 0px rgb(0, 85, 255);
		margin:0;
	}
</style>
